const { ethers, upgrades } = require("hardhat");

async function main() {
    console.log("🔄 开始升级合约...");

    // 从部署信息文件读取合约地址
    const fs = require('fs');
    let deploymentInfo;

    try {
        const data = fs.readFileSync('deployment-info.json', 'utf8');
        deploymentInfo = JSON.parse(data);
    } catch (error) {
        console.error("❌ 无法读取部署信息文件，请先运行部署脚本");
        process.exit(1);
    }

    const [deployer] = await ethers.getSigners();
    console.log("升级者地址:", deployer.address);

    try {
        // 1. 升级价格预言机合约
        console.log("\n📊 升级价格预言机合约...");
        const PriceOracleV2 = await ethers.getContractFactory("PriceOracle");
        const upgradedPriceOracle = await upgrades.upgradeProxy(
            deploymentInfo.contracts.PriceOracle,
            PriceOracleV2
        );
        console.log("✅ PriceOracle 升级完成:", upgradedPriceOracle.address);

        // 2. 升级NFT合约
        console.log("\n🎨 升级NFT合约...");
        const AuctionNFTV2 = await ethers.getContractFactory("AuctionNFT");
        const upgradedNFT = await upgrades.upgradeProxy(
            deploymentInfo.contracts.AuctionNFT,
            AuctionNFTV2
        );
        console.log("✅ AuctionNFT 升级完成:", upgradedNFT.address);

        // 3. 升级拍卖工厂合约
        console.log("\n🏭 升级拍卖工厂合约...");
        const AuctionFactoryV2 = await ethers.getContractFactory("AuctionFactory");
        const upgradedFactory = await upgrades.upgradeProxy(
            deploymentInfo.contracts.AuctionFactory,
            AuctionFactoryV2
        );
        console.log("✅ AuctionFactory 升级完成:", upgradedFactory.address);

        // 4. 验证升级
        console.log("\n🔍 验证升级结果...");

        // 检查合约是否仍然正常工作
        const ethPrice = await upgradedPriceOracle.getETHPrice();
        const nftName = await upgradedNFT.name();
        const factoryOwner = await upgradedFactory.owner();

        console.log("ETH价格:", ethers.utils.formatUnits(ethPrice, 8), "USD");
        console.log("NFT名称:", nftName);
        console.log("工厂所有者:", factoryOwner);

        // 5. 更新部署信息
        deploymentInfo.lastUpgrade = {
            timestamp: new Date().toISOString(),
            upgrader: deployer.address,
            version: "v2"
        };

        fs.writeFileSync(
            'deployment-info.json',
            JSON.stringify(deploymentInfo, null, 2)
        );

        console.log("\n✅ 所有合约升级完成!");
        console.log("📝 升级信息已更新到 deployment-info.json");

    } catch (error) {
        console.error("\n❌ 升级失败:", error);
        process.exit(1);
    }
}

main()
    .then(() => {
        console.log("\n🎉 升级完成!");
        process.exit(0);
    })
    .catch((error) => {
        console.error("❌ 升级脚本执行失败:", error);
        process.exit(1);
    });
